package com.uiotsoft.small.host.sampler.simple;

import cn.hutool.json.JSONUtil;
import com.uiotsoft.small.mqtt.MqttClientOld;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HostBusinessSampler extends AbstractJavaSamplerClient {
    private volatile MqttClientOld clientOld;
    private String pubTopic;
    private String subTopic;
    private String sendMsg;
    private static final Logger log = LoggerFactory.getLogger(HostBusinessSampler.class);
    private int receiveType;
    private String msgId;

    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("pubTopic", "");
        params.addArgument("sendMsg", "");
        params.addArgument("subTopic", "");
        params.addArgument("receiveType", "1");
        return params;
    }

    private void setupValues(JavaSamplerContext context) {
        pubTopic = context.getParameter("pubTopic");
        sendMsg = context.getParameter("sendMsg");
        subTopic = context.getParameter("subTopic");
        receiveType = Integer.parseInt(context.getParameter("receiveType"));
        msgId = JSONUtil.parseObj(sendMsg).getJSONObject("header").getStr("msgId");
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        setupValues(javaSamplerContext);
        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        SampleResult results = new SampleResult();
        results.sampleStart();
        clientOld = (MqttClientOld) vars.getObject("clientOldHost");
        if (clientOld != null){
            boolean publish = clientOld.hostPublish(pubTopic, sendMsg);
            if (publish){
                if (!subTopic.equals("") && subTopic != null){
                    boolean flag = false;
                    int num = 0;
                    if (receiveType>100){
                        flag = true;
                    }
                    long start = System.currentTimeMillis();
                    while (true){
                        String topic = clientOld.getTopic();
                        String result = clientOld.getResult();
                        if (result != null && topic != null){
                            String msgIdReceive = JSONUtil.parseObj(result).getJSONObject("header").getStr("msgId");
                            if (topic.equals(subTopic) && msgIdReceive.equals(msgId)){
                                num ++;
                                if (num == receiveType){
                                    log.info("\n******客户端接收消息成功……\n******msgId：{}\n******clientId：{}\n******topic：{}:\n******content{}",msgId,clientOld.getClientId(),topic,result);
                                    results.setSuccessful(true);
                                    results.setResponseData(result, "UTF-8");
                                    results.setResponseCodeOK();
                                    break;
                                }
                            }
                        }

                        if (flag){
                            long end = System.currentTimeMillis();
                            if (end-start > receiveType){
                                log.info("\n******客户端{}接收消息超时……",clientOld.getClientId());
                                results.setSuccessful(false);
                                results.setResponseData("receive timeout", "UTF-8");
                                results.setResponseCode("500");
                                break;
                            }
                        }

                    }
                }else {
                    results.setSuccessful(true);
                    results.setResponseData("publish success", "UTF-8");
                    results.setResponseCodeOK();
                }
            }else {
                results.setSuccessful(false);
                results.setResponseData("publish fail", "UTF-8");
                results.setResponseCode("400");
            }
        }else {
            results.setSuccessful(false);
            results.setResponseData("connect null", "UTF-8");
            results.setResponseCode("500");
        }
        results.sampleEnd();
        return results;
    }
}
